from flask import Blueprint

sysUser_bp = Blueprint('sys_user', __name__)
from Test import db
import datetime
import hashlib
from flask import Flask, request, jsonify, abort, g
from utils.tokenUtil import *
import json


import re


# 用户类
class User(db.Model):
    __tablename__ = 'sys_user'
    user_id = db.Column(db.Integer, primary_key=True)
    user_name = db.Column(db.String(255))
    email = db.Column(db.String(255))
    password = db.Column(db.String(255))
    preference = db.Column(db.Text)
    occupation = db.Column(db.String(255))
    industry = db.Column(db.String(255))
    target = db.Column(db.String(255))
    preference_area = db.Column(db.String(255))
    chat_id = db.Column(db.Text)
    free_times = db.Column(db.Integer, nullable=True)
    vip_id = db.Column(db.Integer, nullable=True)
    vip_expire = db.Column(db.DateTime)
    create_time = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    update_time = db.Column(db.DateTime, default=datetime.datetime.utcnow(), onupdate=datetime.datetime.utcnow())



##创建用户接口

@sysUser_bp.route('/user/register', methods=['POST'])
def create_user():
    data = request.get_json()
    user_name = data['user_name']
    ##针对邮箱号添加校验
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    validate_email_result = re.match(pattern, data['email']) is not None
    if not validate_email_result:
        return jsonify({
            'data': '',
            'message': 'Modify user email failed. Email format incorrect',
            'status': 500
        })

    ##针对用户名是否重复添加校验
    existing_user = User.query.filter_by(user_name=user_name).first()
    if existing_user:
        return jsonify({
            'data': '',
            'message': 'User with this username already exists',
            'status': 500
        })

    ##针对密码进行md5加密处理
    origin_password = data['password']
    md = hashlib.md5(origin_password.encode())
    md5password = md.hexdigest()

    # 获取当前时间戳

    now = datetime.datetime.now()

    # 格式化为 YYYYMMDDHHMMSS 格式
    formatted_time = now.strftime("%Y%m%d%H%M%S")

    new_user = User(
        user_name=user_name,
        password=md5password,
        email=data['email'],
        chat_id = formatted_time + '&&&&'+ user_name,
        create_time=datetime.datetime.utcnow(),
        update_time=datetime.datetime.utcnow()
    )
    db.session.add(new_user)
    db.session.commit()
    return jsonify({
        'data': new_user.user_name,
        'message': 'User registration successful',
        'status': 200
    })


##查看用户详情接口
@sysUser_bp.route('/users', methods=['GET'])
@token_required
def get_user():
    user = User.query.get(g.user_id)
    if user is None:
        return jsonify({
            'data': {},
            'message': 'User not found',
            'status': 500
        })
    else:
        preference_list = []
        if user.preference:
            preference_list = json.loads(user.preference)
        industry_list = []
        if user.industry:
            industry_list = json.loads(user.industry)
        target_list = []
        if user.target:
            target_list = json.loads(user.target)
        preference_area_list = []
        if user.preference_area:
            preference_area_list = json.loads(user.preference_area)

        return jsonify({
            'data': {
                'user_id': user.user_id,
                'email': user.email,
                'preference': preference_list,
                'create_time': user.create_time,
                'update_time': user.update_time,
                'user_name': user.user_name,
                'occupation': user.occupation,
                'industry': industry_list,
                'target': target_list,
                'preference_area': preference_area_list,
                'chat_id': user.chat_id
            },
            'message': 'User found',
            'status': 200
        })


@sysUser_bp.route('/user/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('user_name')
    origin_password = data.get('password')

    ##判断用户名称是否存在
    existing_user = User.query.filter_by(user_name=username).first()
    if not existing_user:
        return jsonify({
            'data': {},
            'message': 'User with this username not exists',
            'status': 500
        })

    ##针对密码进行md5加密处理
    md = hashlib.md5(origin_password.encode())
    md5password = md.hexdigest()

    # 密码认证逻辑
    if existing_user.password == md5password:
        token = generate_token(existing_user.user_id)
        return jsonify({
            'data': {
                'token': token,
                'username': username
            },
            'message': 'success',
            'status': 200
        })
    else:
        return jsonify({
            'data': {},
            'message': 'Login failed! Please verify the username or password',
            'status': 500
        })


@sysUser_bp.route('/user/modify-email', methods=['POST'])
@token_required
def update_user_email():
    data = request.json
    email = data.get('email')
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    validate_email_result = re.match(pattern, email) is not None
    if not validate_email_result:
        return jsonify({
            'data': {},
            'message': 'Modify user email failed. Email format incorrect',
            'status': 500
        })
    # 查找用户
    user = User.query.get(g.user_id)
    user.email = email
    user.update_time = datetime.datetime.utcnow()
    db.session.commit()
    return jsonify({
        'data': {},
        'message': 'Change User Email Successfully',
        'status': 200
    })


@sysUser_bp.route('/user/modify-password', methods=['POST'])
@token_required
def update_user_password():
    data = request.json
    password = data.get('password')
    # 查找用户
    user = User.query.get(g.user_id)

    ##针对密码进行md5加密处理
    md = hashlib.md5(password.encode())
    md5password = md.hexdigest()
    user.password = md5password
    user.update_time = datetime.datetime.utcnow()
    db.session.commit()
    return jsonify({
        'data': {},
        'message': 'Change User Password Successfully',
        'status': 200
    })


@sysUser_bp.route('/user/modify-preference', methods=['POST'])
@token_required
def update_user_preference():
    data = request.json
    # 查找用户
    user = User.query.get(g.user_id)
    user.preference = json.dumps(data.get('preference'))
    user.industry = json.dumps(data.get('industry'))
    user.target = json.dumps(data.get('target'))
    user.preference_area = json.dumps(data.get('preference_area'))
    user.occupation = data.get('occupation')

    user.update_time = datetime.datetime.utcnow()
    db.session.commit()
    return jsonify({
        'data': {},
        'message': 'Change User Preference Successfully',
        'status': 200
    })